from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash

app = Flask(__name__)
# NOTE: 添加secret_key配置以支持session功能
app.config['SECRET_KEY'] = 'your-secret-key-here'  # 生产环境应使用更安全的随机字符串
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///menu.db'
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'))


class Role(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)


class Menu(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    url = db.Column(db.String(255), nullable=False)
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'))


with app.app_context():
    db.create_all()

    # 添加示例角色
    if not Role.query.filter_by(name='admin').first():
        role1 = Role(name='admin')
        db.session.add(role1)
    if not Role.query.filter_by(name='user').first():
        role2 = Role(name='user')
        db.session.add(role2)
    db.session.commit()

    # 添加示例用户
    if not User.query.filter_by(username='admin').first():
        hashed_password1 = generate_password_hash('admin')
        role1 = Role.query.filter_by(name='admin').first()
        user1 = User(username='admin', password=hashed_password1, role_id=role1.id)
        db.session.add(user1)

    if not User.query.filter_by(username='user').first():
        hashed_password2 = generate_password_hash('user')
        role2 = Role.query.filter_by(name='user').first()
        user2 = User(username='user', password=hashed_password2, role_id=role2.id)
        db.session.add(user2)
    
    # NOTE: 添加示例菜单数据
    if not Menu.query.first():
        admin_role = Role.query.filter_by(name='admin').first()
        user_role = Role.query.filter_by(name='user').first()
        
        # 管理员菜单
        admin_menus = [
            ('Dashboard', '/admin/dashboard'),
            ('User Management', '/admin/users'),
            ('System Settings', '/admin/settings')
        ]
        
        # 普通用户菜单
        user_menus = [
            ('Profile', '/user/profile'),
            ('Orders', '/user/orders')
        ]
        
        # 添加管理员菜单
        for name, url in admin_menus:
            menu = Menu(name=name, url=url, role_id=admin_role.id)
            db.session.add(menu)
        
        # 添加用户菜单
        for name, url in user_menus:
            menu = Menu(name=name, url=url, role_id=user_role.id)
            db.session.add(menu)
    
    db.session.commit()


from flask import render_template, request, redirect, url_for, session
from werkzeug.security import check_password_hash


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        hashed_password = generate_password_hash(password)
        new_user = User(username=username, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('login'))
    return render_template('register.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        if user and check_password_hash(user.password, password):
            session['user_id'] = user.id
            return redirect(url_for('home'))
        else:
            return 'Invalid username or password'
    return render_template('login.html')


@app.route('/home')
def home():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    user = User.query.get(session['user_id'])
    if user.role_id:
        menus = Menu.query.filter_by(role_id=user.role_id).all()
    else:
        menus = []
    menu_items = [(menu.name, menu.url) for menu in menus]
    return render_template('home.html', menu_items=menu_items, user=user)

@app.route('/logout')
def logout():
    session.pop('user_id', None)
    return redirect(url_for('login'))


if __name__ == '__main__':
    app.run(debug=True,port=9001)
